<?php
namespace app\admin\core;

class Context {
    const SESSION_PREFIX = 'weipeter_';
    const SESSION_KEY_CONTEXT = 'context';
    /**
     * @var array 消息上下文
     * [
     *  name    // 控制器名
     *  time    // 到期时间
     *  data    // array,消息上下文保存的数据
     * ]
     */
    private $_name = 'null';
    private $_openid;
    private $_mpSession;
    public function __construct($openid)
    {
        $this->_openid = $openid;
        $this->_mpSession = new MpSession($openid);
        $this->_mpSession->setPrefix(self::SESSION_PREFIX);

        $context = $this->_mpSession->get(self::SESSION_KEY_CONTEXT);
        if($context && $context['time'] < time()) {
            // 过期
            $this->endContext();
        }else {
            $this->_name = $context['name'];
        }
    }
    public function setName($name) {
        $this->_name = $name;
    }
    public function getName() {
        return $this->_name;
    }
    public function inContext() {
        $context = $this->_mpSession->get(self::SESSION_KEY_CONTEXT);
        if($this->_mpSession->get(self::SESSION_KEY_CONTEXT)) {
            return true;
        }else {
            return false;
        }
    }
    public function beginContext($second,$data = []) {
        $context = [];
        $context['time'] = time() + $second;
        $context['name'] = $this->_name;
        $context['data'] = $data;
        $this->_mpSession->set(self::SESSION_KEY_CONTEXT,$context);
    }
    public function getData() {
        $context = $this->_mpSession->get(self::SESSION_KEY_CONTEXT);
        return $context['data'];
    }
    public function keepContext($second,$data = []) {
        $context = $this->_mpSession->get(self::SESSION_KEY_CONTEXT);
        $context['time'] = time() + $second;
        $context['data'] = $data;
        $this->_mpSession->set(self::SESSION_KEY_CONTEXT,$context);
    }
    public function endContext() {
        $this->_mpSession->rm(self::SESSION_KEY_CONTEXT);
    }
}